import wave

import pyaudio
import requests
import time
import threading

# 配置参数
FORMAT = pyaudio.paInt16  # 音频格式
CHANNELS = 1  # 单声道
RATE = 16000  # 采样率
CHUNK = int(60 * 10 / 10 / 1000 * RATE * 2)  # 每帧的大小，根据你的stride计算
# samp_width = 2 # 采样宽度，16位音频是2字节

# 打开音频流
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)

def audio_stream_to_api():
    try:
        while True:
            # 读取音频数据
            frames = []
            for i in range(0, int(RATE / CHUNK * 10)):
                data = stream.read(CHUNK, exception_on_overflow=False)
                frames.append(data)
            audio_bytes = b''.join(frames)
            # 转换为 WAV 格式
            # with wave.open('request.wav', 'wb') as f:
            #     f.setnchannels(CHANNELS)
            #     f.setsampwidth(samp_width)
            #     f.setframerate(RATE)
            #     print("Audio data is saving to request.wav")
            #     f.writeframes(audio_bytes)
            # 发送音频数据到 FastAPI 服务
            response = requests.post('http://localhost:9000/voice-ai', data=audio_bytes)
            if response.status_code == 200:
                result = response.json()
                print("Response Text:", result['text'])
                # 这里你可以将音频数据保存或直接播放
                audio_response = result['audio']
                # 保存或播放音频的代码...
                with wave.open('Response.wav', 'wb') as f:
                    f.setnchannels(CHANNELS)
                    f.setsampwidth(CHUNK)
                    f.setframerate(RATE)
                    print("Audio data is saving to Response.wav")
                    f.writeframes(audio_response)
            else:
                print("Error:", response.status_code)
    except KeyboardInterrupt:
        print("Stopped by user.")
    finally:
        stream.stop_stream()
        stream.close()
        audio.terminate()


def read_audio_data():
    # 读取一个音频文件并发送到 FastAPI 服务
    with wave.open('request.wav', 'rb') as f:
        audio_bytes = f.readframes(f.getnframes())
        response = requests.post('http://localhost:9000/voice-ai', data=audio_bytes)
    if response.status_code == 200:
        result = response.json()
        print("Response Text:", result['text'])
        # 这里你可以将音频数据保存或直接播放
        audio_response = result['audio']
        # 保存或播放音频的代码...
        with wave.open('Response.wav', 'wb') as f:
            f.setnchannels(CHANNELS)
            f.setsampwidth(CHUNK)
            f.setframerate(RATE)
            print("Audio data is saving to Response.wav")
            f.writeframes(audio_response)
    else:
        print("Error:", response.status_code)


# 启动音频流线程
thread = threading.Thread(target=read_audio_data)
thread.start()